import requests
import json
from util import md5, compose_wav_header
import base64

PWD = 'password001'

def tts_gen(xinput, xusername=''):
    xjson = dict()
    xjson['input'] = xinput
    xjson['username'] = xusername

    xcheck = xinput + PWD
    xcheck = md5(xcheck)
    xjson['check'] = xcheck

    res = requests.post('http://127.0.0.1:7771/api', json=xjson)
    xjson = json.loads(res.text)
    xoutput = xjson['output']
    xoutput = base64.b64decode(xoutput)
    return xoutput


if '__main__' == __name__:

    # xjson = dict()
    # xjson['input'] = '您好！怎么去八达岭？'
    # res = requests.post('http://127.0.0.1:7777/api', json=xjson)
    # xjson = json.loads(res.text)
    # print(xjson)

    xinput = '我们的学习很有思意呀！'
    print('input:', xinput)
    xoutput = tts_gen(xinput)
    xlen = len(xoutput)
    xhead = compose_wav_header(xlen)
    xaudio = xhead + xoutput
    with open('app_test_tts.tmp.wav', 'bw') as f:
        f.write(xaudio)
    print('All over.')
